<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #msglist {
      width: 400px;
      height: 500px;
      background: #eeeeee;
    }
  </style>
</head>

<body>
  <div id="msglist">

  </div>
  <textarea id="msg" rows="5" cols="10">

  </textarea>
  <button id="btn">留言</button>

  <script>

    var $btn = document.querySelector("#btn");
    var $msg = document.querySelector("#msg")
    var $list = document.querySelector('#msglist')

    //http => new WebSocket('ws://***')
    //https => new WebSocket('wss://***') 不能是ip
    var ws = new WebSocket('ws://localhost:8099')

    function wsEvent() {
      //用于指定当从服务器接受到信息时的回调函数
      ws.onmessage = (msg) => {
        console.log(msg.data)
        $list.innerHTML += msg.data + '<br>';
      }

      //用于连接成功之后的回调函数
      ws.onopen = () => {
        console.log('open ...')
      }

      //用于指定连接关闭后的回调函数
      ws.onclose = () => {
        console.log('close')
        reconnect()
      }

      ws.onerror = () => {
        console.log('error')
        reconnect()
      }

    }

    wsEvent();

    $btn.addEventListener('click', () => {
      //数据的发送
      ws.send($msg.value)

    })

    //重连
    function reconnect() {
      if (ws.readyState === 2 || ws.readyState === 3) {
        ws = new WebSocket('ws://localhost:8099');
        wsEvent();
      }
    }

  </script>

</body>

</html>